//
//  BasicFunction.swift
//  yc-basic-common
//
//  Created by 董鹏 on 2022/1/19.
//

import UIKit

/**
 * 十六进制颜色转换
 */
public func hexColor(_ hex: String, alpha: CGFloat = 1.0) -> UIColor?{
    guard hex.count >= 6 else {
        return nil
    }
    let hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines)
    let scanner = Scanner(string: hexString)
     
    if hexString.hasPrefix("#") {
        scanner.scanLocation = 1
    }
     
    var color: UInt32 = 0
    scanner.scanHexInt32(&color)
     
    let mask = 0x000000FF
    let r = Int(color >> 16) & mask
    let g = Int(color >> 8) & mask
    let b = Int(color) & mask
     
    let red   = CGFloat(r) / 255.0
    let green = CGFloat(g) / 255.0
    let blue  = CGFloat(b) / 255.0
    
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
/**
 * 当前APP版本号
 */
public var CURRENTAPPLICATIONVERSION:String {
    get{
        let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
        return version
    }
}
/**
 * 加粗字体
 */
public func mediumFont(size: CGFloat = 17) -> UIFont?{
    return UIFont(name: "PingFangSC-Medium", size: size)
}
/**
* 常规字体
*/
public func regularFont(size: CGFloat = 17) -> UIFont?{
    return UIFont(name: "PingFangSC-Regular", size: size)
}

/**
 * 输入颜色生成图片
 */
public func imageWithColor(color: UIColor) -> UIImage?{
    let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
/**
 * 加载Bundle图片
 */
public func getBundleImage(bundle: Bundle, name: String) -> UIImage?{
    let image = UIImage(named: name, in: bundle, compatibleWith: nil)
    return image
}

/**
 * 获取当前控制器
 */
public func getCurrentViewController(base: UIViewController? = UIApplication.shared.delegate?.window??.rootViewController) -> UIViewController? {
    if let nav = base as? UINavigationController {
        return getCurrentViewController(base: nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
        return getCurrentViewController(base: tab.selectedViewController)
    }
    if let presented = base?.presentedViewController {
        return getCurrentViewController(base: presented)
    }
    return base
}
/**
 * 屏幕宽度
 */
public let kScreenWidth: CGFloat = UIScreen.main.bounds.width
/**
 * 屏幕高度
 */
public let kScreenHeight: CGFloat = UIScreen.main.bounds.height
/**
 * 获取UUID
 */
public var conversionUUID:String{
    get {
        // 初始的UUID 带 -
        let originallyUUID = UIDevice.current.identifierForVendor!.uuidString
        // 移除UUID中的 -
        let conversionUUID = originallyUUID.replacingOccurrences(of: "-", with: "")
        return conversionUUID
    }
}

/**
 * 是否是暗黑模式
 */
public func isDarkMode() -> Bool?{
    if #available(iOS 13.0, *) {
        if UITraitCollection.current.userInterfaceStyle == .dark {
            return true
        }else {
            return false
        }
    } else {
        return false
    }
}

/// 底部安全距离
public func getTabbarSafeBottomMargin() -> CGFloat {
    var safeBottom:CGFloat = 0
    if #available(iOS 11, *) {
        let safeArea = UIApplication.shared.keyWindow?.safeAreaInsets
        safeBottom = safeArea?.bottom ?? 0
    }
    return safeBottom
}

/// 状态栏的高度
public func getStatusBarHight() -> CGFloat {
    var statusBarHeight:CGFloat = 0
    if #available(iOS 13.0, *) {
        let statusBarManager = UIApplication.shared.windows.first?.windowScene?.statusBarManager
        statusBarHeight = statusBarManager?.statusBarFrame.size.height ?? 0
    }else{
        statusBarHeight = UIApplication.shared.statusBarFrame.size.height
    }
    return statusBarHeight
}


/// 是否刘海屏
public func isIPhoneX() -> Bool{
    if #available(iOS 11, *) {
        guard let w = UIApplication.shared.delegate?.window, let unwrapedWindow = w else {
            return false
        }
        if unwrapedWindow.safeAreaInsets.left > 0 || unwrapedWindow.safeAreaInsets.bottom > 0 {
            return true
        }
    }
    return false
}
 
/// 计算文本宽高
/// - Parameters:
///   - textStr: 文字
///   - size: 最大大小
///   - font: 字号
/// - Returns: 实际大小
public func calculateLableSizeString(textStr:String,size:CGSize,font:UIFont) -> CGSize {
    let lableText = textStr
    let options : NSStringDrawingOptions =
            NSStringDrawingOptions.usesLineFragmentOrigin
    let string:NSString = lableText as NSString
    let boundingRect = string.boundingRect(with: size,  options: options, attributes: [NSAttributedString.Key.font:font],context: nil)
    return boundingRect.size
}

func getStoryBoardVC(identifier: String) -> RViewController {
    let mainBundle = Bundle.main
    let main = UIStoryboard(name: "Main", bundle: mainBundle)
    let vc = main.instantiateViewController(withIdentifier: identifier)
    return vc as! RViewController
}

/// 格式化时间戳
func formatTimeStamp(time:TimeInterval ,format:String? = "yyyy-MM-dd HH:mm:ss") -> String {
    let timeInterval = TimeInterval(time)
    let date = Date.init(timeIntervalSince1970: timeInterval)
    let dateFormatte = DateFormatter()
    dateFormatte.dateFormat = format
    return dateFormatte.string(from: date)
}

/// 字符串转时间戳
func timeStrChangeToTimeInterval(timeStr: String, dateFormat: String?) -> TimeInterval {
    let format = DateFormatter.init()
    format.dateStyle = .medium
    format.timeStyle = .short
    if dateFormat == nil {
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
    }else {
        format.dateFormat = dateFormat
    }
    let date = format.date(from: timeStr)
    return date!.timeIntervalSince1970
}

///  second 秒数 转为 x天x时x分x秒
func FormatDate(second:Int) -> String {
    
    let formatter = DateComponentsFormatter.init()
    // . dropMiddle为  0d 00h 00m 格式 (需要其它格式可以自己点进去看看)
    formatter.zeroFormattingBehavior = .dropMiddle
    
    // 此处事例只写了 日 时 分；需要秒的可以在后面加上（参数： | NSCalendar.Unit.second.rawValue ）
    formatter.allowedUnits = NSCalendar.Unit(rawValue: NSCalendar.Unit.day.rawValue | NSCalendar.Unit.hour.rawValue | NSCalendar.Unit.minute.rawValue | NSCalendar.Unit.second.rawValue)
    
    formatter.unitsStyle = DateComponentsFormatter.UnitsStyle.abbreviated
    
    // 结果默认格式为 1d 1h 1m
    var resultStr = formatter.string(from: TimeInterval(second)) ?? ""
    
    // 处理为 1天 1小时 1分钟 （根据自己需求处理）
    resultStr = resultStr.replacingOccurrences(of: "d", with: "天", options: .literal, range: nil)
    resultStr = resultStr.replacingOccurrences(of: "h", with: "时", options: .literal, range: nil)
    resultStr = resultStr.replacingOccurrences(of: "m", with: "分", options: .literal, range: nil)
    resultStr = resultStr.replacingOccurrences(of: "s", with: "秒", options: .literal, range: nil)
    
    return resultStr
    
}

/// 分享文件
func shareFile(url: URL) {
    let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)
    activity.excludedActivityTypes = [.addToReadingList, .print, .assignToContact,
                                      .addToReadingList, .openInIBooks, .markupAsPDF]
    UIApplication.shared.windows[0].rootViewController?.present(activity, animated: true) {
    }
}

/// 沙盒下document路径
func documentPath() -> String {
    let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).map(\.path).last
    return url ?? ""
}

//MARK: 改变图片颜色
extension UIImage {
    /// 更改图片颜色
    public func maskImageWithColor(color : UIColor) -> UIImage{
        UIGraphicsBeginImageContext(self.size)
        color.setFill()
        let bounds = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIRectFill(bounds)
        self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
    }
}
